// React类型导入
import type React from "react";
// React Hooks
import { useEffect, useState } from "react";
// Ant Design组件
import { Breadcrumb, Layout, Menu, theme, Select, Switch, Button } from "antd";
// Ant Design图标
import {
  BulbOutlined,
  MoonOutlined,
  CaretRightOutlined,
} from "@ant-design/icons";
// 路由配置
import { homeRouder } from "../../router";
// React Router相关
import { Outlet, useLocation, useNavigate } from "react-router-dom";
// 国际化
import { useTranslation } from "react-i18next";

// 解构Layout组件
const { Header, Content, Footer, Sider } = Layout;

/**
 * 菜单项类型定义
 */
type MenuItem = {
  label: string;           // 菜单标签
  key: string;             // 菜单键值
  icon?: React.ReactNode;  // 菜单图标
  children?: MenuItem[];   // 子菜单
};

/**
 * 原始菜单项类型定义
 */
type RawMenuItem = {
  title: string;           // 菜单标题
  path: string;            // 菜单路径
  icon?: React.ReactNode;  // 菜单图标
  children?: RawMenuItem[]; // 子菜单
};

/**
 * 主题管理Hook
 * 管理应用的主题模式（亮色/暗色）
 * @returns [主题模式, 设置主题模式函数]
 */
function useTheme(): [string, Dispatch<SetStateAction<string>>] {
  const nav = useNavigate();
  // 从本地存储获取主题模式，默认为亮色
  const [themeMode, setThemeMode] = useState<string>(
    localStorage.getItem("themeMode") || "light"
  );
  
  // 当主题模式改变时，更新DOM和本地存储
  useEffect(() => {
    document.documentElement.setAttribute("data-theme", themeMode);
    document.body.setAttribute("data-theme", themeMode);
    localStorage.setItem("themeMode", themeMode);
  }, [themeMode]);
  
  return [themeMode, setThemeMode];
}

/**
 * 主布局组件
 * 包含侧边栏、顶部导航、内容区域和底部
 */
const Home: React.FC = () => {
  // 国际化语言设置
  const [I18n] = useState(localStorage.getItem("I18n") || "zh");
  // 国际化hook
  const { t, i18n } = useTranslation();
  // 当前路径
  const { pathname } = useLocation();
  // 用户信息
  const data = localStorage.getItem("userInfo") || "{}";
  const { avator, nickname } = JSON.parse(data);
  // 路由导航
  const nav = useNavigate();
  // 侧边栏折叠状态
  const [collapsed, setCollapsed] = useState(false);
  // Ant Design主题token
  const {
    token: { colorBgContainer, borderRadiusLG },
  } = theme.useToken();
  // 主题管理
  const [themeMode, setThemeMode] = useTheme();
  // 主题切换动画状态
  const [isSwitching, setIsSwitching] = useState(false);
  // 主题切换遮罩颜色
  const [maskColor, setMaskColor] = useState("#fff");
  
  /**
   * 将原始菜单项转换为Ant Design菜单项格式
   * @param arry 原始菜单项数组
   * @returns 转换后的菜单项数组
   */
  const rouder = (arry: RawMenuItem[]): MenuItem[] => {
    return arry.map((item) => {
      return {
        label: t(`${item.title}`),  // 使用国际化翻译
        key: item.path,
        icon: item.icon,
        children: item.children ? rouder(item.children) : null,
      };
    });
  };
  
  // 生成菜单项
  const items = rouder(homeRouder as RawMenuItem[]);
  
  // 初始化国际化语言
  useEffect(() => {
    handleChange(I18n);
    // eslint-disable-next-line
  }, [I18n]);
  
  /**
   * 处理语言切换
   * @param value 语言代码
   */
  const handleChange = (value: string) => {
    localStorage.setItem("I18n", value);
    i18n.changeLanguage(value);
  };
  
  /**
   * 处理主题切换
   * @param checked 是否切换到暗色主题
   */
  const handleThemeSwitch = (checked: boolean) => {
    setMaskColor(checked ? "#001529" : "#fff");
    setIsSwitching(true);
    // 动画一半时切换主题
    setTimeout(() => {
      setThemeMode(checked ? "dark" : "light");
    }, 300);
    // 动画结束后移除动画层
    setTimeout(() => {
      setIsSwitching(false);
    }, 600);
  };
  
  /**
   * 退出登录
   * 清除本地存储的用户信息并跳转到登录页
   */
  const tuic = () => {
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
    nav("/login");
  };
  
  return (
    <div>
      {/* 主题切换动画遮罩 */}
      {isSwitching && (
        <div
          className="theme-switch-mask"
          style={
            {
              background: maskColor,
              "--mask-color": maskColor,
              pointerEvents: "none",
              zIndex: 99999,
              position: "fixed",
              top: 0,
              left: 0,
              right: 0,
              bottom: 0,
            } as React.CSSProperties
          }
        />
      )}
      
      {/* 主布局 */}
      <Layout style={{ minHeight: "100vh" }}>
        {/* 侧边栏 */}
        <Sider
          collapsible
          collapsed={collapsed}
          onCollapse={(value) => setCollapsed(value)}
          theme={themeMode === "dark" ? "dark" : "light"}
        >
          {/* 侧边栏Logo */}
          <div className="demo-logo-vertical" />
          
          {/* 侧边栏菜单 */}
          <Menu
            theme={themeMode === "dark" ? "dark" : "light"}
            defaultSelectedKeys={[pathname]}
            mode="inline"
            items={items}
            onClick={({ key }) => nav(key)}
          >
            
          </Menu>
        </Sider>
        
        {/* 主内容区域 */}
        <Layout>
          {/* 顶部导航栏 */}
          <Header style={{ padding: 0, background: "var(--header-bg)" }}>
            {/* 主题和语言切换区域 */}
            <div
              style={{
                position: "absolute",
                right: "240px",
                top: "0px",
                display: "flex",
                alignItems: "center",
                gap: 8,
              }}
            >
              {/* 主题切换开关 */}
              <Switch
                checked={themeMode === "dark"}
                checkedChildren={<MoonOutlined />}
                unCheckedChildren={<BulbOutlined />}
                onChange={handleThemeSwitch}
                style={{ marginRight: 8 }}
              />
              <span>{themeMode === "light" ? "🌙 " : "☀️ "}</span>
              
              {/* 语言选择器 */}
              <Select
                defaultValue={I18n}
                style={{ width: 120 }}
                onChange={handleChange}
                options={[
                  { value: "zh", label: "中文" },
                  { value: "en", label: "英文" },
                  { value: "jn", label: "日语" },
                ]}
              />
            </div>
            
            {/* 用户信息区域 */}
            <div
              style={{
                position: "absolute",
                right: "20px",
                top: "0",
                display: "flex",
                alignItems: "center",
              }}
            >
              {/* 用户头像 */}
              <img
                src={avator}
                alt=""
                style={{ width: "50px", height: "50px" }}
              />
              {/* 用户昵称 */}
              <span className="admin-username">{nickname}</span>
              {/* 退出登录按钮 */}
              <Button danger style={{ marginLeft: "10px" }} onClick={tuic}>
                退出登录
              </Button>
              
            </div>
          </Header>
          
          {/* 内容区域 */}
          <Content style={{ margin: "0 16px" }}>
            {/* 面包屑导航 */}
            <Breadcrumb
              style={{ margin: "16px 0" }}
              items={[{ title: "User" }, { title: "Bill" }]}
            />
            {/* 主要内容容器 */}
            <div
              style={{
                padding: 24,
                minHeight: 360,
                background: colorBgContainer,
                borderRadius: borderRadiusLG,
              }}
            >
              {/* 路由出口 - 渲染子路由内容 */}
              <Outlet></Outlet>
            </div>
          </Content>
          
          {/* 底部 */}
          <Footer style={{ textAlign: "center" }}>
            Ant Design ©{new Date().getFullYear()} Created by Ant UED
          </Footer>
        </Layout>
      </Layout>
    </div>
  );
};

// 导出主布局组件
export default Home;
